package fr.neticar.webremoteclient.server;

import java.awt.Graphics2D;
import java.awt.Image;
import java.awt.Rectangle;
import java.awt.image.BufferedImage;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.nio.ByteBuffer;

import javax.imageio.ImageIO;

public class ImageUtils {

	public static BufferedImage getImage(Image i, Rectangle clipZone) {
		BufferedImage image = new BufferedImage(clipZone.width, clipZone.height, BufferedImage.TYPE_INT_RGB);
		Graphics2D g2 = (Graphics2D) image.getGraphics();
		g2.drawImage(i, -clipZone.x, -clipZone.y, null);
		return image;
	}

	public static ImageContentBean convertToJPEG(BufferedImage image) throws IOException {
		ByteArrayOutputStream bos = new ByteArrayOutputStream();
		ImageIO.write(image, "jpeg", bos);
		int length = bos.size();
		ByteBuffer buffer = ByteBuffer.wrap(bos.toByteArray());
		ImageContentBean contentBean = new ImageContentBean(buffer, "image/jpeg", length);
		return contentBean;
	}
}
